from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

from config import MYSQL_CONFIG

db = SQLAlchemy()

class Place(db.Model):
    __tablename__ = 'places'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    category = db.Column(db.String(50), nullable=False)
    budget = db.Column(db.Float, nullable=False)
    latitude = db.Column(db.Float, nullable=False)
    longitude = db.Column(db.Float, nullable=False)
    duration = db.Column(db.Integer, nullable=False)

def init_app(app):
    app.config['SQLALCHEMY_DATABASE_URI'] = (
        f"mysql+pymysql://{MYSQL_CONFIG['user']}:{MYSQL_CONFIG['password']}@"
        f"{MYSQL_CONFIG['host']}:{MYSQL_CONFIG['port']}/{MYSQL_CONFIG['database']}"
    )
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    
    with app.app_context():
        try:
            with db.engine.connect() as conn:
                conn.execute(text("SELECT 1")).scalar()
        except Exception as e:
            raise RuntimeError(f"数据库连接测试失败: {str(e)}")